#include "OutputManager.h"

OutputManager::OutputManager(
    int timeNum, int clientNum, int siteNum,
    const std::vector<std::string> &clientName,
    const std::vector<std::string> &siteName)
    : timeNum(timeNum),
      clientNum(clientNum),
      siteNum(siteNum),
      clientName(clientName),
      siteName(siteName)
{
    log.resize(timeNum + 1);
    for (auto &i : log)
    {
        i.resize(clientNum + 1);
    }
}

void OutputManager::setTime(int timeID)
{
    if (timeID < 1 || timeID > timeNum)
    {
        std::cerr << "[OutputManager Error]setTime(int timeID):timeID is incorrect.(" << timeID << ")";
        return;
    }
    this->nowTime = timeID;
}

void OutputManager::setClient(int clientID)
{
    if (clientID < 1 || clientID > clientNum)
    {
        std::cerr << "[OutputManager Error]setClient(int clientID):clientID is incorrect.(" << clientID << ")";
        return;
    }
    this->nowClient = clientID;
}

void OutputManager::writeLog(int timeID, int clientID, int siteID, int flow)
{
    if (timeID < 1 || timeID > timeNum)
    {
        std::cerr << "[OutputManager Error]writeLog(int timeID, int clientID, int siteID, int flow):timeID is incorrect.(" << timeID << ")";
        return;
    }
    if (clientID < 1 || clientID > clientNum)
    {
        std::cerr << "[OutputManager Error]writeLog(int timeID, int clientID, int siteID, int flow):clientID is incorrect.(" << clientID << ")";
        return;
    }
    if (siteID < 1 || siteID > siteNum)
    {
        std::cerr << "[OutputManager Error]writeLog(int timeID, int clientID, int siteID, int flow):siteID is incorrect.(" << siteID << ")";
        return;
    }
    log[timeID][clientID].push_back(std::make_pair(siteID, flow));
}

void OutputManager::writeLog(int siteID, int flow)
{
    if (siteID < 1 || siteID > siteNum)
    {
        std::cerr << "[OutputManager Error]writeLog(int siteID, int flow):siteID is incorrect.(" << siteID << ")";
        return;
    }
    log[nowTime][nowClient].push_back(std::make_pair(siteID, flow));
}

void OutputManager::writeFile(std::string filePath)
{
    std::ofstream file(filePath);
    for (int i = 1; i <= timeNum; ++i)
    {
        for (int j = 1; j <= clientNum; ++j)
        {
            file << clientName[j] << ":";
            int size = log[i][j].size();
            auto &nowLog = log[i][j];
            for (int k = 0; k < size; ++k)
            {
                auto &nowPair = log[i][j][k];
                file << "<" << siteName[nowPair.first] << ", " << nowPair.second << ">";
                if (k != size - 1)
                    file << ",";
            }
            file << "\n";
        }
    }
}

void OutputManager::clearOutputInfor()
{
    this->nowTime = this->nowClient = 0;
    log.clear();
    log.resize(timeNum + 1);
    for (auto& i : log)
    {
        i.resize(clientNum + 1);
    }
}
